package com.alibaba.cirtus.ots.application.app.ability.facade.v2serviceimpl;

import com.alibaba.citrus.ots.common.annotation.ProcessInvoker;
import com.alibaba.cz.base.tool.Nullable;
import com.alibaba.cz.base.tool.StringUtil;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.alibaba.lattice2.epoch.user.dto.LoginUser;
import com.alibaba.lattice2.epoch.user.service.EpochLoginUserService;
import com.epoch.app.bcorder.model.dto.QueryCargoZoneByIdRequest;
import com.epoch.app.bcorder.model.dto.QueryCargoZoneByIdResponse;
import com.epoch.app.bcorder.model.dto.*;
import com.epoch.app.bcorder.service.BaseDataService;
import com.epoch.app.bcorder.service.PlatformEnhanceService;
import com.epoch.app.bcorder.service.UnifiedInventoryService;
import com.epoch.app.crplatformenhance.goodsfavorites.dto.QueryGoodsFavoritesRequest;
import com.epoch.app.crplatformenhance.goodsfavorites.model.GoodsFavorites;
import com.epoch.app.crplatformenhance.goodsfavorites.service.GoodsFavoritesService;
import com.epoch.app.crplatformenhance.sdo.OrganizationSDO;
import com.epoch.app.crpricecenter.api.creditquery.dto.QueryCompanyToGroupCreditListRequest;
import com.epoch.app.crpricecenter.api.creditquery.service.CreditQueryService;
import com.epoch.app.crpricecenter.model.dto.CompanyToGroupCreditResponse;
import com.epoch.app.crunifiedinventory.allocateapplyordergoods.service.AllocateApplyOrderGoodsService;
import com.epoch.app.crunifiedinventory.api.allocateapplyorderdropdownselection.dto.QueryBranchCustomersRequest;
import com.epoch.app.crunifiedinventory.api.allocateapplyorderdropdownselection.service.AllocateApplyOrderDropDownSelectionService;
import com.epoch.app.crunifiedinventory.api.allocateapplyorderread.service.AllocateApplyOrderReadService;
import com.epoch.app.crunifiedinventory.api.allocateapplyorderwrite.service.AllocateApplyOrderWriteService;
import com.epoch.app.crunifiedinventory.api.forecastwarehouse.dto.QueryDeliveryWarehouseByTypeRequest;
import com.epoch.app.crunifiedinventory.api.forecastwarehouse.dto.QueryReceivingWarehouseByTypeRequest;
import com.epoch.app.crunifiedinventory.api.forecastwarehouse.service.ForecastWarehouseService;
import com.epoch.app.crunifiedinventory.dto.request.QueryAllocateApplyOrderRequest;
import com.epoch.app.crunifiedinventory.dto.response.AllocateApplyOrderDetailDTO;
import com.epoch.app.crunifiedinventory.dto.response.DeliveryWarehouseChoiceDTO;
import com.epoch.app.crunifiedinventory.model.dto.AllocateApplyOrderDetailCreateDTO;
import com.epoch.app.crunifiedinventory.model.dto.AllocateApplyOrderUpdateDTO;
import com.epoch.app.crunifiedinventory.model.dto.*;
import com.epoch.app.crunifiedinventory.service.CrUnifiedInventoryService;
import com.epoch.app.mninventorycenter.model.dto.TransferForecastOrderCreateDetail;
import com.epoch.app.mninventorycenter.model.dto.TransferForecastOrderCreateRequest;
import com.epoch.app.mninventorycenter.model.dto.TransferForecastOrderCreateResponse;
import com.epoch.app.mninventorycenter.transferforecastorderwrite.service.TransferForecastOrderWriteService;
import com.epoch.app.otsapplicationadaptersdk.model.dto.GetOrgByIdRequest;
import com.epoch.app.otsapplicationadaptersdk.model.dto.SaleOrgDTO;
import com.epoch.app.otsapplicationadaptersdk.service.OtsApplicationAdapterSdkService;
import com.epoch.app.otsapplicationappsdk.transfercreate.dto.AsyncRequest;
import com.epoch.app.otsapplicationappsdk.transfercreate.dto.InitRequest;
import com.epoch.app.otsapplicationappsdk.transfercreate.dto.SubmitRequest;
import com.epoch.app.otsapplicationappsdk.transfercreate.service.TransferCreateService;
import com.epoch.app.otspricecenter.api.pricequery.service.PriceQueryService;
import com.epoch.app.otspricecenter.dto.request.*;
import com.epoch.app.otspricecenter.dto.response.ItemPriceResponse;
import com.epoch.app.otspricecenter.dto.response.PriceQueryResponse;
import com.epoch.app.otsunifiedinventory.sdo.enums.AllocateOrderTypeEnum;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

import static org.apache.commons.lang3.time.DateUtils.addDays;


@Service
public class TransferCreateV2ServiceImpl implements TransferCreateService {

    private static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
    private static final String DATE_FORMAT = "yyyy-MM-dd";
    private static final String ZERO_TIME = "00:00:00";

    /**
     * 价格类型 ZMN1 到岸价
     */
    private static final String ZMN1 = "ZMN1";

    private static Log log = Log.getLogger(TransferCreateV2ServiceImpl.class);

    @Resource
    AllocateApplyOrderReadService allocateApplyOrderReadService;

    @Resource
    AllocateApplyOrderWriteService allocateApplyOrderWriteService;

    @Resource
    BaseDataService baseDataService;

//    @Resource
//    OtsUnifiedInventoryService otsUnifiedInventoryService;
    @Resource
    CrUnifiedInventoryService otsUnifiedInventoryService;

    @Resource
    AllocateApplyOrderDropDownSelectionService allocateApplyOrderDropDownSelectionService;
    @Resource
    PlatformEnhanceService platformEnhanceService;

    @Resource
    ForecastWarehouseService forecastWarehouseService;

    @Resource
    UnifiedInventoryService unifiedInventoryService;

    @Resource
    private GoodsFavoritesService favoritesService;

    @Resource
    private CreditQueryService creditQueryService;
    //总部销售组织编码 默认6000
    private static final String SALE_ORGANIZATION_CODE = "6000";

    @Resource
    private AllocateApplyOrderGoodsService allocateApplyOrderGoodsService;

    @Resource
    private TransferForecastOrderWriteService transferForecastOrderWriteService;

    @Resource
    private EpochLoginUserService epochLoginUserService;

    @Override
    public Object init(InitRequest initRequest) {
        log.info("调拨预报单创建渲染 请求参数 {} " , JSONObject.toJSONString(initRequest));
        JSONObject result = new JSONObject();
        JSONObject data = new JSONObject();
        try {
            //当前用户收藏夹货品
            List goodsFavoritesList = new ArrayList();
            try {
                Result<List<GoodsFavorites>> listResult = favoritesService.queryGoodsFavorites(new QueryGoodsFavoritesRequest());
                if (Objects.nonNull(listResult)&& CollectionUtils.isNotEmpty(listResult.getResult())){
                    GoodsFavorites goodsFavorites = listResult.getResult().get(0);
                    JSONArray goodsList = JSONArray.parseArray(goodsFavorites.getGoodsList());
                    if (CollectionUtils.isNotEmpty(goodsList)) {
                        for (Object goodsObj : goodsList) {
                            JSONObject goodsJson = (JSONObject) JSONObject.toJSON(goodsObj);
                            goodsFavoritesList.add(goodsJson.getString("goodsCode"));
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }


            Result<AllocateApplyOrderDetailDTO> callApiResult = null;
            if (initRequest.getCode() != null) {
                try {
                    QueryAllocateApplyOrderRequest queryAllocateApplyOrderRequest = new QueryAllocateApplyOrderRequest();
                    queryAllocateApplyOrderRequest.setCode(initRequest.getCode());
                    callApiResult = allocateApplyOrderReadService.queryAllocateApplyOrderByCode(queryAllocateApplyOrderRequest);

                    AllocateApplyOrderDetailDTO applyAllocate = callApiResult.getResult();
                    if (Objects.nonNull(applyAllocate)){
                        data.put("customerActualAvailableAmount", applyAllocate.getCustomerActualAvailableAmount());
                        data.put("allowPlacedOrderAmount",applyAllocate.getAllowPlacedOrderAmount());
                    }
                    data.put("detailData", applyAllocate);
                } catch (Exception e) {
                    log.info("调拨预报单创建渲染 调拨预报单详情API异常");
                    e.printStackTrace();
                }
            }


            try {
                //单据类型
                Object  allocateApplyOrderDropDownSelection = allocateApplyOrderDropDownSelectionService.queryDocumentType();
                data.put("allocationType",allocateApplyOrderDropDownSelection);
            } catch (Exception e) {
                log.info("调拨预报单创建渲染 单据类型API异常");
                e.printStackTrace();
            }


            try {
                //提报组织
                LoginEmployeeSubmissionOrganizationSelectResponse loginEmployeeSubmissionOrganizationSelectResponse = baseDataService.loginEmployeeSubmissionOrganizationSelect(new LoginEmployeeSubmissionOrganizationSelectRequest());
                log.info("调拨预报单创建渲染 提报组织结果 {} ",JSONObject.toJSONString(loginEmployeeSubmissionOrganizationSelectResponse));
                data.put("organizationSelect",loginEmployeeSubmissionOrganizationSelectResponse.getResult());
            } catch (Exception e) {
                log.info("调拨预报单创建渲染 提报组织API异常");
                e.printStackTrace();
            }


            try {
                //收货仓 类型 组织
                QueryReceivingWarehouseByTypeRequest queryReceivingWarehouseByTypeRequest = new QueryReceivingWarehouseByTypeRequest();
                //callApiResult不为空为编辑状态，发货仓下拉框数据为该单子的单据类型和组织维度下的数据
                if (callApiResult != null && callApiResult.getResult() != null &&
                    callApiResult.getResult().getType() != null && callApiResult.getResult().getApplyOrg() != null) {
                    queryReceivingWarehouseByTypeRequest.setType(callApiResult.getResult().getType());
                    queryReceivingWarehouseByTypeRequest.setApplyOrgId(String.valueOf(callApiResult.getResult().getApplyOrg()));
                } else {
                    queryReceivingWarehouseByTypeRequest.setType("1");
                }
                log.info("调拨预报单创建渲染 收货仓API入参 {} ",JSONObject.toJSONString(queryReceivingWarehouseByTypeRequest));
                Result<List<DeliveryWarehouseChoiceDTO>> forecastWarehouseResult = forecastWarehouseService.queryReceivingWarehouseByType(queryReceivingWarehouseByTypeRequest);
                log.info("调拨预报单创建渲染 收货仓API出参 {} ",JSONObject.toJSONString(forecastWarehouseResult));
                data.put("receivingWarehouse",forecastWarehouseResult.getResult());
            } catch (Exception e) {
                log.info("调拨预报单创建渲染 收货仓API异常");
                e.printStackTrace();
            }

            try {
                //货品组
                GetScItemGroupSelectResponse scItemGroupSelect = baseDataService.getScItemGroupSelect();
                data.put("scItemGroupSelect",scItemGroupSelect.getResult());
            } catch (Exception e) {
                log.info("调拨预报单创建渲染 货品组API异常");
                e.printStackTrace();
            }


            try {
                //发货仓 单据类型
                QueryDeliveryWarehouseByTypeRequest queryDeliveryWarehouseByTypeRequest = new QueryDeliveryWarehouseByTypeRequest();
                //callApiResult不为空为编辑状态，发货仓下拉框数据为该单子的单据类型和组织维度下的数据
                if (callApiResult != null && callApiResult.getResult() != null && callApiResult.getResult().getType() != null) {
                    queryDeliveryWarehouseByTypeRequest.setType(callApiResult.getResult().getType());
                } else {
                    queryDeliveryWarehouseByTypeRequest.setType("1");
                }
                log.info("调拨预报单创建渲染 发货仓API入参 {} ",JSONObject.toJSONString(queryDeliveryWarehouseByTypeRequest));
                Result<List<DeliveryWarehouseChoiceDTO>> deliveryWarehouse = forecastWarehouseService.queryDeliveryWarehouseByType(queryDeliveryWarehouseByTypeRequest);
                log.info("调拨预报单创建渲染 发货仓API出参 {} ",JSONObject.toJSONString(deliveryWarehouse));
                data.put("deliveryWarehouse",deliveryWarehouse.getResult());
            } catch (Exception e) {
                log.info("调拨预报单创建渲染 发货仓API异常");
                e.printStackTrace();
            }

            try {
                //货品明细
                //前端透传常用货品code，下发到接口返回常用货品类目
                QueryGoodsListRequest queryGoodsListRequest = new QueryGoodsListRequest();
                queryGoodsListRequest.setRecentlyUsedItemIdList(initRequest.getGoodsIdList());
                if (CollectionUtils.isNotEmpty(goodsFavoritesList)) {
                    queryGoodsListRequest.setGoodsFavoritesList(goodsFavoritesList);
                }
                Result<List<QueryGoodsListResponse>> queryGoodsListResponse = platformEnhanceService.queryGoodsList(queryGoodsListRequest);
                data.put("goodsList",queryGoodsListResponse.getResult());
//                data.put("goodsList",buildGoodsList(queryGoodsListResponse.getResult(),initRequest.getGoodsIdList()));
            } catch (Exception e) {
                log.info("调拨预报单创建渲染 货品明细API异常");
                e.printStackTrace();
            }


            try {
                //运输方式
                Object transportModeMap = otsUnifiedInventoryService.transportModeReadServiceImplQueryTransportMode();
                JSONObject transportJson = (JSONObject)JSONObject.toJSON(transportModeMap);
                data.put("transport",transportJson.getJSONArray("result"));
            } catch (Exception e) {
                log.info("调拨预报单创建渲染 运输方式API异常");
                e.printStackTrace();
            }

            try {
                //分公司客户
                Result<List<BranchCustomersDTO>> branchCustomers  = allocateApplyOrderDropDownSelectionService.queryBranchCustomers(new QueryBranchCustomersRequest());
                log.info("调拨预报单创建渲染 分公司客户结果 {} ",JSONObject.toJSONString(branchCustomers));
                if (branchCustomers != null) {
                    data.put("branchCustomersDTOS",branchCustomers.getResult());
                }
            } catch (Exception e) {
                log.info("调拨预报单创建渲染 分公司客户API异常");
                e.printStackTrace();
            }


            result.put("success",true);
            result.put("result",data);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("调拨预报单创建渲染异常 {} " , e.getMessage());
            result.put("success",false);
            result.put("message","调拨预报单创建渲染异常");
        }

        return result;
    }

    private static String replaceTimeWithZero(String dateTimeStr) {
        // 将日期和零时间组合成新的日期时间字符串
        return dateTimeStr + " " + ZERO_TIME;
    }

    @Override
    public Object async(AsyncRequest asyncRequest) {
        JSONObject result = new JSONObject();
        JSONObject data = new JSONObject();
        JSONObject asyncJson = new JSONObject();
        try {
            log.info("调拨预报单创建异步 请求参数 {} ", JSON.toJSONString(asyncRequest));
            JSONObject request = (JSONObject)JSONObject.toJSON(asyncRequest.getRequest());

            JSONObject fieldsJson = new JSONObject();
            if (request != null) {
                if (request.get("fields") != null) {
                    fieldsJson = request.getJSONObject("fields");
                    if (fieldsJson.getJSONObject("bizModel") != null) {
                        data = fieldsJson.getJSONObject("bizModel").getJSONObject("result");
                    }
                    asyncJson = fieldsJson.getJSONObject("asyncJson");
                }
            }
            asyncJson.remove("customerActualAvailableAmount");
            asyncJson.remove("allowPlacedOrderAmount");
            data.remove("customerActualAvailableAmount");
            data.remove("allowPlacedOrderAmount");
            if (asyncJson.get("type") != null && asyncJson.get("applyOrg") != null) {
                try {
                    //收货仓
                    QueryReceivingWarehouseByTypeRequest queryReceivingWarehouseByTypeRequest = new QueryReceivingWarehouseByTypeRequest();
                    queryReceivingWarehouseByTypeRequest.setType(fieldsJson.getString("type"));
                    queryReceivingWarehouseByTypeRequest.setApplyOrgId(asyncJson.getString("applyOrg"));
                    log.info("调拨预报单创建异步 收货仓API入参 {} ", JSONObject.toJSONString(queryReceivingWarehouseByTypeRequest));
                    Result<List<DeliveryWarehouseChoiceDTO>> forecastWarehouseResult = forecastWarehouseService.queryReceivingWarehouseByType(queryReceivingWarehouseByTypeRequest);
                    log.info("调拨预报单创建异步 收货仓API出参 {} ", JSONObject.toJSONString(forecastWarehouseResult));
                    data.put("receivingWarehouse", forecastWarehouseResult.getResult());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (AllocateOrderTypeEnum.HEADQUARTER_SALES.getType().equals(asyncJson.getInteger("type"))){
                    //客户实际可发货金额
                    String customerActualAvailableAmount="";
                    //可以预报订单金额
                    String allowPlacedOrderAmount="";
                    QueryCompanyToGroupCreditListRequest queryCompanyToGroupCreditListRequest = new QueryCompanyToGroupCreditListRequest();
                    queryCompanyToGroupCreditListRequest.setLimit(100);
                    queryCompanyToGroupCreditListRequest.setCompanyId(asyncJson.getString("applyOrg"));
                    Result<List<CompanyToGroupCreditResponse>> response = creditQueryService.queryCompanyToGroupCreditList(queryCompanyToGroupCreditListRequest);
                    if (Objects.nonNull(response)&&CollectionUtils.isNotEmpty(response.getResult())){
                        CompanyToGroupCreditResponse companyToGroupCreditResponse = response.getResult().get(0);
                        customerActualAvailableAmount=companyToGroupCreditResponse.getCustomerActualAvailableAmountStr();
                        allowPlacedOrderAmount=companyToGroupCreditResponse.getAllowPlacedOrderAmount();
                    }
                    data.put("customerActualAvailableAmount",customerActualAvailableAmount);
                    data.put("allowPlacedOrderAmount",allowPlacedOrderAmount);
                }

            }
            if (fieldsJson.get("type") != null) {
                try {
                    //发货仓
                    QueryDeliveryWarehouseByTypeRequest queryDeliveryWarehouseByTypeRequest = new QueryDeliveryWarehouseByTypeRequest();
                    queryDeliveryWarehouseByTypeRequest.setType(fieldsJson.getString("type"));
                    log.info("调拨预报单创建异步 发货仓API入参 {} ",JSONObject.toJSONString(queryDeliveryWarehouseByTypeRequest));
                    Result<List<DeliveryWarehouseChoiceDTO>> deliveryWarehouse = forecastWarehouseService.queryDeliveryWarehouseByType(queryDeliveryWarehouseByTypeRequest);
                    log.info("调拨预报单创建异步 发货仓API出参 {} ",JSONObject.toJSONString(deliveryWarehouse));
                    data.put("deliveryWarehouse",deliveryWarehouse.getResult());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            Integer type = asyncJson.getInteger("type");
            if (Objects.nonNull(type)){
                boolean needCheckMultiple=Boolean.FALSE;
                if (AllocateOrderTypeEnum.PLAN.getType().equals(type)||AllocateOrderTypeEnum.HEADQUARTER_SALES.getType().equals(type)) {
                    needCheckMultiple=Boolean.TRUE;
                }
                asyncJson.put("needCheckMultiple",needCheckMultiple);

            }

            data.put("asyncJson",asyncJson);

            result.put("success",true);
            result.put("result",data);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("调拨预报单创建异步渲染 异常 {}", e.getMessage());
            result.put("success",false);
            result.put("message",e.getMessage() != null ? e.getMessage() : "调拨预报单创建异步渲染异常");
        }


        log.info("调拨预报单创建异步渲染 出参 {} ", JSON.toJSONString(result));
        return result;
    }


    @Override
    @ProcessInvoker(remark = "TransferCreate$submit", errorCode = "OTS-02-007-00-16-999")
    public Object submit(SubmitRequest submitRequest) {
        log.info("调拨预报单创建提交 请求参数 {} " , JSON.toJSONString(submitRequest));
        JSONObject result = new JSONObject();
        try {
            JSONObject request = (JSONObject)JSONObject.toJSON(submitRequest.getRequest());

            JSONObject bizModel = null;
            String submitType = null;
            JSONObject submitFields = null;
            if (request != null) {
                if (request.get("fields") != null) {
                    submitType  = request.getJSONObject("fields").getString("submitType");
                    submitFields = request.getJSONObject("fields").getJSONObject("submitFields");
                    bizModel = request.getJSONObject("fields").getJSONObject("bizModel");
                }
            }

            if (submitFields != null) {
                Result<AllocateApplyOrderDetailDTO> allocateApplyOrderDetailDTOResult = allocateApplyOrderSubmit(submitFields,submitType);
                if (!allocateApplyOrderDetailDTOResult.isSuccess()) {
                    result.put("success",false);
                    result.put("message",allocateApplyOrderDetailDTOResult.getMessage());
                    return result;
                }
                if (bizModel != null) {
                    bizModel.getJSONObject("result").put("detailData",allocateApplyOrderDetailDTOResult.getResult());
                }
            }

            if ("submit".equals(submitType)) {
                result.put("message","提交成功");
            } else if ("save".equals(submitType)) {
                result.put("message","保存成功");
            }
            result.put("success",true);
            if ("save".equals(submitType)) {
                result.put("message","保存成功");
            } else if ("submit".equals(submitType)) {
                result.put("message","提交成功");
            }
            result.put("result",bizModel.get("result"));
        } catch (Exception e) {
            log.error("调拨预报单创建提交 异常 {} " , e.getMessage(), e);
            result.put("success",false);
        }
        return result;
    }

    private Result<AllocateApplyOrderDetailDTO> oneStockSubmit(JSONObject submitFields, String submitType) {
        Result<AllocateApplyOrderDetailDTO> allocateApplyOrderDetailResult = new Result<>();

        Result<Boolean> checkResult = checkOneStockParams(submitFields,submitType);
        if (!checkResult.isSuccess()) {
            allocateApplyOrderDetailResult.setMessage(checkResult.getMessage());
            allocateApplyOrderDetailResult.setSuccess(false);
            return allocateApplyOrderDetailResult;
        }

        TransferForecastOrderCreateRequest createRequest = new TransferForecastOrderCreateRequest();
        //小程序创建标识
        createRequest.setIsAppCreate(true);

        createRequest.setApplyOrg(submitFields.getLong("applyOrg") == null ? "6136" : submitFields.getLong("applyOrg").toString());
        createRequest.setTransferForecastOrderType(submitFields.getInteger("type") == null ? "1" : submitFields.getInteger("type").toString());
        createRequest.setRemark(submitFields.getString("remark"));

        Date hopeDeliveryTime = new Date(submitFields.getLong("hopeDeliveryTime"));
        String expectedDeliveryDateTime = new SimpleDateFormat(DATE_FORMAT).format(hopeDeliveryTime);
        String expectedDeliveryDate = replaceTimeWithZero(expectedDeliveryDateTime);
        // 替换时间部分为 00:00:00
        createRequest.setExpectedDeliveryDate(expectedDeliveryDate);

        // 单据日期=当天日期
        Date orderDate = new Date();
        String orderDateTime = new SimpleDateFormat(DATE_FORMAT).format(orderDate);
        String orderDateStr = replaceTimeWithZero(orderDateTime);
        createRequest.setOrderDate(orderDateStr);

        //生效日期 = 当前10点前创建的，生效日期放当天的日期；当天10点后创建的，生效日期放第二天的日期。
        // 获取当天10点的时间
        Date effectiveDate;
        if (orderDate.before(getTodayAt10AM())) {
            effectiveDate = orderDate;
            createRequest.setEffectiveDate(orderDateStr);
        } else {
            Date date = addDays(orderDate, 1);
            effectiveDate = date;
            String dateStr = new SimpleDateFormat(DATE_FORMAT).format(date);
            String newDateStr = replaceTimeWithZero(dateStr);
            createRequest.setEffectiveDate(newDateStr);
        }

        // 失效日期=生效日期+1天
        Date expirationDate = addDays(effectiveDate, 1);
        String invalid = new SimpleDateFormat(DATE_FORMAT).format(expirationDate);
        String invalidDate = replaceTimeWithZero(invalid);
        createRequest.setInvalidDate(invalidDate);

        createRequest.setShipMethodCode(submitFields.getString("shipMethod"));
        createRequest.setBusinessType(submitFields.getInteger("goodsGroup") == null ? "11" : submitFields.getInteger("goodsGroup").toString());

        QueryCargoZoneByIdRequest queryCargoZoneByIdRequest = new QueryCargoZoneByIdRequest();
        String shipWarehouseId = submitFields.getString("shipWarehouseId");
        String receiveWarehouseId = submitFields.getString("receiveWarehouseId");
        queryCargoZoneByIdRequest.setCargoZoneIdList(Lists.newArrayList(shipWarehouseId, receiveWarehouseId));
        QueryCargoZoneByIdResponse cargoZoneByIdResponse = unifiedInventoryService.queryCargoZoneById(queryCargoZoneByIdRequest);
        if (cargoZoneByIdResponse == null || CollectionUtils.isEmpty(cargoZoneByIdResponse.getResult()) || cargoZoneByIdResponse.getResult().size() != 2) {
            allocateApplyOrderDetailResult.setMessage("查询收发货仓失败");
            allocateApplyOrderDetailResult.setSuccess(false);
            return allocateApplyOrderDetailResult;
        }
        Map<String, JSONObject> warehouseIdMap = new HashMap<>();
        JSONArray array = JSON.parseArray(JSON.toJSONString(cargoZoneByIdResponse.getResult()));
        for (int i = 0; i < array.size(); i++) {
            JSONObject jsonObject = array.getJSONObject(i);
            warehouseIdMap.put(jsonObject.getString("id"), jsonObject);
        }

        createRequest.setDeliveryLogicWarehouseCode(warehouseIdMap.get(shipWarehouseId).getString("code"));
        createRequest.setReceiveLogicWarehouseCode(warehouseIdMap.get(receiveWarehouseId).getString("code"));

        //获取小程序当前登录人的总部销售组织编码 默认 6000
        Result<OrganizationSDO> saleOrganizationCode = otsUnifiedInventoryService.getSaleOrganizationCode();
        createRequest.setHeadquartersOrganizationCode(Optional.ofNullable(saleOrganizationCode)
                .map(Result::getResult).map(OrganizationSDO::getCode).orElse(SALE_ORGANIZATION_CODE));
        createRequest.setHeadquartersChannelCode("90");
        createRequest.setFromSys("APP_OMNI");
        createRequest.setOrderTag("03");
        createRequest.setBizUnit("6136");
        LoginUser loginUser = epochLoginUserService.getLoginUser();
        String operatorId = "";
        if (loginUser != null) {
            operatorId = StringUtils.isNotBlank(loginUser.getRealName()) ? loginUser.getRealName() : loginUser.getEmpId();
        }
        createRequest.setCreator(operatorId);
        String requestId = UUID.randomUUID().toString();
        createRequest.setRequestId(requestId.replaceAll("-", ""));
        List<TransferForecastOrderCreateDetail> list = new ArrayList<>();

        JSONArray jsonArray = submitFields.getJSONArray("submitGoods");

        if (CollectionUtils.isNotEmpty(jsonArray)) {
            for (Object goodsObj : jsonArray) {
                JSONObject goods = (JSONObject) JSONObject.toJSON(goodsObj);
                TransferForecastOrderCreateDetail detail = new TransferForecastOrderCreateDetail();
                detail.setGoodsCode(goods.getString("goodsCode"));
                detail.setQuantity(goods.getInteger("goodsNum").toString());
                detail.setRemark(goods.getString("remark"));
                detail.setUnit("PC");
                list.add(detail);
            }
        }


        createRequest.setTransferForecastOrderCreateDetailList(list);
        if ("submit".equals(submitType)) {
            createRequest.setSubmitFlag("true");
        } else {
            createRequest.setSubmitFlag("false");
        }

        log.info("一盘货调拨预报单创建提交|request={}" , JSON.toJSONString(createRequest));

        Result<TransferForecastOrderCreateResponse> createResult = transferForecastOrderWriteService.createTransferForecastOrderV2(createRequest);

        if (!createResult.isSuccess() || createResult.getResult() == null){
            allocateApplyOrderDetailResult.setMessage(createResult.getMessage());
            allocateApplyOrderDetailResult.setSuccess(false);
            return allocateApplyOrderDetailResult;
        }
        QueryAllocateApplyOrderRequest queryAllocateApplyOrderRequest = new QueryAllocateApplyOrderRequest();
        queryAllocateApplyOrderRequest.setCode(createResult.getResult().getTransferForecastOrderCode());
        Result<AllocateApplyOrderDetailDTO> callApiResult = allocateApplyOrderReadService.queryAllocateApplyOrderByCode(queryAllocateApplyOrderRequest);
        if (!callApiResult.isSuccess()) {
            allocateApplyOrderDetailResult.setMessage(callApiResult.getMessage());
            allocateApplyOrderDetailResult.setSuccess(false);
            return allocateApplyOrderDetailResult;
        }

        return callApiResult;
    }


    public Result<AllocateApplyOrderDetailDTO> allocateApplyOrderSubmit(JSONObject submitFields, String submitType) {
        Result<AllocateApplyOrderDetailDTO> allocateApplyOrderDetailResult = new Result<>();

        Result<Boolean> oneStockCheck = isOneStock(submitFields, submitType);
        if (!oneStockCheck.isSuccess()) {
            allocateApplyOrderDetailResult.setSuccess(false);
            allocateApplyOrderDetailResult.setMessage(oneStockCheck.getMessage());
            return allocateApplyOrderDetailResult;
        } else if (oneStockCheck.getResult()) {
            return oneStockSubmit(submitFields,submitType);
        }

        try {
            Result<Boolean> checkResult = checkParams(submitFields,submitType);
            if (!checkResult.isSuccess()) {
                allocateApplyOrderDetailResult.setMessage(checkResult.getMessage());
                allocateApplyOrderDetailResult.setSuccess(false);
                return allocateApplyOrderDetailResult;
            }
            String  code = submitFields.getString("code");
            Long id = submitFields.getLong("id");
            if (code == null) {
                //未创建
                AllocateApplyOrderCreateDTO allocateApplyOrderCreateDTO = new AllocateApplyOrderCreateDTO();
                allocateApplyOrderCreateDTO.setIsDTC(false);
                //小程序创建标识
                allocateApplyOrderCreateDTO.setIsAppCreate(true);
                allocateApplyOrderCreateDTO.setApplyOrgId(submitFields.getLong("applyOrg"));
                allocateApplyOrderCreateDTO.setType(submitFields.getInteger("type"));
                allocateApplyOrderCreateDTO.setRemark(submitFields.getString("remark"));


                if (submitFields.get("hopeDeliveryTime") != null) {
                    allocateApplyOrderCreateDTO.setHopeDeliveryTime(new Date(submitFields.getLong("hopeDeliveryTime")));
                }
                allocateApplyOrderCreateDTO.setShipMethod(submitFields.getString("shipMethod"));
                allocateApplyOrderCreateDTO.setGoodsGroup(submitFields.getInteger("goodsGroup"));
                allocateApplyOrderCreateDTO.setShipWarehouseId(submitFields.getString("shipWarehouseId"));
                allocateApplyOrderCreateDTO.setReceiveWarehouseId(submitFields.getInteger("receiveWarehouseId"));
                allocateApplyOrderCreateDTO.setCustomerActualAvailableAmount(submitFields.getString("customerActualAvailableAmount"));
                allocateApplyOrderCreateDTO.setAllowPlacedOrderAmount(submitFields.getString("allowPlacedOrderAmount"));

                try {
                    if (submitFields.getInteger("receiveWarehouseId") != null) {
                        QueryCargoZoneByIdRequest queryCargoZoneByIdRequest = new QueryCargoZoneByIdRequest();
                        queryCargoZoneByIdRequest.setCargoZoneIdList(Lists.newArrayList(String.valueOf(submitFields.getInteger("receiveWarehouseId"))));
                        QueryCargoZoneByIdResponse queryCargoZoneByIdResponse = unifiedInventoryService.queryCargoZoneById(queryCargoZoneByIdRequest);
                        if (Objects.nonNull(queryCargoZoneByIdResponse)&& CollectionUtils.isNotEmpty(queryCargoZoneByIdResponse.getResult())) {
                            Map<String, String> result = (Map<String, String>) queryCargoZoneByIdResponse.getResult().get(0);
                            //总部内部售达方编号
                            allocateApplyOrderCreateDTO.setSapInternalSalesBPCode(result.get("sapInternalSalesBPCode"));
                            //总部内部送达方编号
                            allocateApplyOrderCreateDTO.setSapInternalDeliveryBPCode(result.get("sapInternalDeliveryBPCode"));
                            //总部售达方编号
                            allocateApplyOrderCreateDTO.setSapSalesBPCode(result.get("sapSaleBPCode"));
                            //总部送达方编号
                            allocateApplyOrderCreateDTO.setSapDeliveryBPCode(result.get("sapDeliveryBPCode"));
                        }
                    }
                } catch (Exception e) {
                    log.info("调拨预报单创建提交 unifiedInventoryService.queryCargoZoneById异常");
                    e.printStackTrace();
                }

                //获取小程序当前登录人的总部销售组织编码 默认 6000
                Result<OrganizationSDO> saleOrganizationCode = otsUnifiedInventoryService.getSaleOrganizationCode();
                allocateApplyOrderCreateDTO.setHeadquartersOrganizationCode(Optional.ofNullable(saleOrganizationCode)
                        .map(Result::getResult).map(OrganizationSDO::getCode).orElse(SALE_ORGANIZATION_CODE));

                log.info("调拨预报单创建提交 调创建API参数 {} " , JSONObject.toJSONString(allocateApplyOrderCreateDTO));
                Result<AllocateApplyOrderDetailDTO> allocateApplyOrderDetailDTOResult = allocateApplyOrderWriteService.createAllocateApplyOrder(allocateApplyOrderCreateDTO);
                if (allocateApplyOrderDetailDTOResult.isSuccess()) {
                    code = allocateApplyOrderDetailDTOResult.getResult().getCode();
                    id = allocateApplyOrderDetailDTOResult.getResult().getId();
                } else {
                    allocateApplyOrderDetailResult.setMessage(allocateApplyOrderDetailDTOResult.getMessage());
                    allocateApplyOrderDetailResult.setSuccess(false);
                    return allocateApplyOrderDetailResult;
                }
            }

            AllocateApplyOrderUpdateDTO allocateApplyOrderUpdateDTO = new AllocateApplyOrderUpdateDTO();
            allocateApplyOrderUpdateDTO.setId(id);
            allocateApplyOrderUpdateDTO.setCode(code);
            allocateApplyOrderUpdateDTO.setRemark(submitFields.getString("remark"));
            if (submitFields.get("hopeDeliveryTime") != null) {
                allocateApplyOrderUpdateDTO.setHopeDeliveryTime(new Date(submitFields.getLong("hopeDeliveryTime")));
            }
            allocateApplyOrderUpdateDTO.setShipMethod(submitFields.getString("shipMethod"));
            allocateApplyOrderUpdateDTO.setShipWarehouseId(submitFields.getString("shipWarehouseId"));
            //不传值，提交接口底层获取不到会nep
            allocateApplyOrderUpdateDTO.setIsDTC(false);
            allocateApplyOrderUpdateDTO.setType(submitFields.getString("type"));
//            allocateApplyOrderUpdateDTO.setGoodsGroup(submitFields.getString("goodsGroup"));
            //工厂直发编辑
            if (submitFields.getBooleanValue("factory")) {
                //编辑状态下，客户地址，客户名称，分公司客户不可编辑
//                allocateApplyOrderUpdateDTO.setCustomerAddress(submitFields.getString("customerAddress"));
//                allocateApplyOrderUpdateDTO.setCustomer(submitFields.getString("customer"));
                allocateApplyOrderUpdateDTO.setIsDTC(true);
            } else {
                allocateApplyOrderUpdateDTO.setReceiveWarehouseId(submitFields.getInteger("receiveWarehouseId"));
            }

            List<AllocateApplyOrderDetailCreateDTO> list = new ArrayList<>();
            if (submitFields.get("submitGoods") != null) {
                JSONArray jsonArray = submitFields.getJSONArray("submitGoods");
                if (CollectionUtils.isNotEmpty(jsonArray)) {
                    for (Object goodsObj : jsonArray) {
                        JSONObject goods = (JSONObject) JSONObject.toJSON(goodsObj);
                        AllocateApplyOrderDetailCreateDTO allocateApplyOrderDetailCreateDTO = new AllocateApplyOrderDetailCreateDTO();
                        allocateApplyOrderDetailCreateDTO.setTitle(goods.getString("goodsName"));
                        allocateApplyOrderDetailCreateDTO.setApplyQuantity(goods.getInteger("goodsNum"));
                        allocateApplyOrderDetailCreateDTO.setGoodsId(goods.getString("id"));
                        allocateApplyOrderDetailCreateDTO.setScItemId(goods.getString("goodsCode"));
                        allocateApplyOrderDetailCreateDTO.setRemark(goods.getString("remark"));
                        allocateApplyOrderDetailCreateDTO.setLineNo(goods.getInteger("goodsDetailsLine"));
                        list.add(allocateApplyOrderDetailCreateDTO);
                    }
                }

            }
            allocateApplyOrderUpdateDTO.setList(list);

            log.info("调拨预报单创建提交 入参 {} " , JSON.toJSONString(allocateApplyOrderUpdateDTO));

            Result<Boolean> updateAllocateApplyOrderResult = null;
            Result<AllocateApplyOrderDetailDTO> submitAllocateApplyOrderResult = null;
            if ("submit".equals(submitType)) {
                //2023.11.28 查询货品的价格
                ApplyOrderQueryGoodsListRequest applyOrderQueryGoodsListRequest = new ApplyOrderQueryGoodsListRequest();
                applyOrderQueryGoodsListRequest.setApplyOrderQueryCode(code);
                applyOrderQueryGoodsListRequest.setCodes(Nullable.stream(allocateApplyOrderUpdateDTO.getList()).map(AllocateApplyOrderDetailCreateDTO::getScItemId).distinct().collect(Collectors.toList()));
                applyOrderQueryGoodsListRequest.setShipWarehouseAreaId(allocateApplyOrderUpdateDTO.getShipWarehouseId());
                Result<List<AllocateApplyOrderQueryGoodsListResponse>> listResult = allocateApplyOrderGoodsService.queryGoodsListQuickly(applyOrderQueryGoodsListRequest);
                if (listResult != null && CollectionUtils.isNotEmpty(listResult.getResult())){
                    List<AllocateApplyOrderQueryGoodsListDateilResponse> goodsListDetailResponses = listResult.getResult().stream().flatMap(res -> res.getGoodsList().stream()).collect(Collectors.toList());
                    allocateApplyOrderUpdateDTO.getList().forEach(detailCreateDTO -> {
                        AllocateApplyOrderQueryGoodsListDateilResponse allocateApplyOrderQueryGoodsListDateilResponse = goodsListDetailResponses.stream().filter(res -> Objects.equals(res.getGoodsCode(), detailCreateDTO.getScItemId()))
                                .findFirst().orElse(null);
                        if (allocateApplyOrderQueryGoodsListDateilResponse != null){
                            detailCreateDTO.setUnitPrice(allocateApplyOrderQueryGoodsListDateilResponse.getPrice());
                        }
                    });
                }
                submitAllocateApplyOrderResult =  allocateApplyOrderWriteService.submitAllocateApplyOrder(allocateApplyOrderUpdateDTO);
                if (submitAllocateApplyOrderResult == null || !submitAllocateApplyOrderResult.isSuccess()){
                    allocateApplyOrderDetailResult.setSuccess(false);
                    allocateApplyOrderDetailResult.setMessage(submitAllocateApplyOrderResult != null ? submitAllocateApplyOrderResult.getMessage() : "保存提交失败");
                    return allocateApplyOrderDetailResult;
                }
            } else if ("save".equals(submitType)) {
                updateAllocateApplyOrderResult =  allocateApplyOrderWriteService.updateAllocateApplyOrder(allocateApplyOrderUpdateDTO);
                if (updateAllocateApplyOrderResult == null || !updateAllocateApplyOrderResult.isSuccess()) {
                    allocateApplyOrderDetailResult.setSuccess(false);
                    allocateApplyOrderDetailResult.setMessage(updateAllocateApplyOrderResult != null ? updateAllocateApplyOrderResult.getMessage() : "保存提交失败");
                    return allocateApplyOrderDetailResult;
                }
            }else {
                allocateApplyOrderDetailResult.setSuccess(false);
                allocateApplyOrderDetailResult.setMessage("保存提交失败");
                return allocateApplyOrderDetailResult;
            }

            QueryAllocateApplyOrderRequest queryAllocateApplyOrderRequest = new QueryAllocateApplyOrderRequest();
            queryAllocateApplyOrderRequest.setCode(code);
            Result<AllocateApplyOrderDetailDTO> callApiResult = allocateApplyOrderReadService.queryAllocateApplyOrderByCode(queryAllocateApplyOrderRequest);

            return callApiResult;
        } catch (Exception e) {
            log.error("调拨预报单创建提交 请求RPC异常", e);
            allocateApplyOrderDetailResult.setSuccess(false);
            allocateApplyOrderDetailResult.setMessage("保存提交失败");
        }
        return allocateApplyOrderDetailResult;
    }

    private Result<Boolean> isOneStock(JSONObject submitFields, String submitType) {
        Result<Boolean> checkResult = checkOneStockParams(submitFields,submitType);
        if (!checkResult.isSuccess()) {
            return checkResult;
        }
        String receiveWarehouseId = submitFields.getString("receiveWarehouseId");
        QueryCargoZoneByIdRequest queryCargoZoneByIdRequest = new QueryCargoZoneByIdRequest();
        queryCargoZoneByIdRequest.setCargoZoneIdList(Lists.newArrayList(receiveWarehouseId));
        QueryCargoZoneByIdResponse cargoZoneByIdResponse = unifiedInventoryService.queryCargoZoneById(queryCargoZoneByIdRequest);
        if (cargoZoneByIdResponse == null || CollectionUtils.isEmpty(cargoZoneByIdResponse.getResult())) {
            checkResult.setMessage("查询收货仓失败");
            checkResult.setSuccess(false);
            return checkResult;
        }
        Map<String, Object> result = (Map<String, Object>) cargoZoneByIdResponse.getResult().get(0);
        Map<String, String> featureMap = (Map<String, String>) result.get("feature");
        String sapCompanyCode = featureMap.get("sapCompanyCode");
        return "6136".equals(sapCompanyCode) ? Result.success(true) : Result.success(false);
    }

    private Result<Boolean> checkOneStockParams(JSONObject submitFields, String submitType) {
        Result<Boolean> result = new Result<>();
        result.setSuccess(true);
        if (submitFields.getInteger("type") == null) {
            result.setMessage("单据类型必填");
            result.setSuccess(false);
            return result;
        }
        if (StringUtils.isBlank(submitFields.getString("shipWarehouseId"))) {
            result.setMessage("发货仓必填");
            result.setSuccess(false);
            return result;
        }
        if (StringUtils.isBlank(submitFields.getString("hopeDeliveryTime"))) {
            result.setMessage("期望交货日期必填");
            result.setSuccess(false);
            return result;
        }

        if (submitFields.getInteger("goodsGroup") == null) {
            result.setMessage("货品组必填");
            result.setSuccess(false);
            return result;
        }
        if (StringUtils.isBlank(submitFields.getString("receiveWarehouseId"))) {
            result.setMessage("收货仓必填");
            result.setSuccess(false);
            return result;
        }

        if (submitFields.get("submitGoods") == null || CollectionUtils.isEmpty(submitFields.getJSONArray("submitGoods"))) {
            result.setMessage("货品明细不能为空");
            result.setSuccess(false);
            return result;
        }

        return result;
    }

    public Result<Boolean> checkParams(JSONObject submitFields, String submitType) {
        Result<Boolean> result = new Result<>();
        result.setSuccess(true);
        if (submitFields.getInteger("type") == null) {
            result.setMessage("单据类型必填");
            result.setSuccess(false);
            return result;
        } else if (submitFields.getString("shipWarehouseId") == null) {
            result.setMessage("发货仓必填");
            result.setSuccess(false);
            return result;
        }  else if (submitFields.getString("hopeDeliveryTime") == null) {
            result.setMessage("期望交货日期必填");
            result.setSuccess(false);
            return result;
        }

        //工厂直发调拨预报单
        if (submitFields.getBooleanValue("factory")) {
            if (submitFields.getString("customer") == null) {
                result.setMessage("客户名称必填");
                result.setSuccess(false);
                return result;
            }
            if (submitFields.getString("customerAddress") == null) {
                result.setMessage("客户地址必填");
                result.setSuccess(false);
                return result;
            }
        } else {
            if (submitFields.getInteger("goodsGroup") == null) {
                result.setMessage("货品组必填");
                result.setSuccess(false);
                return result;
            }
            if (submitFields.getInteger("receiveWarehouseId") == null) {
                result.setMessage("收货仓必填");
                result.setSuccess(false);
                return result;
            }
        }



        if (submitFields.get("submitGoods") == null || org.apache.commons.collections.CollectionUtils.isEmpty(submitFields.getJSONArray("submitGoods"))) {
            result.setMessage("货品明细不能为空");
            result.setSuccess(false);
            return result;
        }

        return result;
    }

    public List<QueryGoodsListResponse> buildGoodsList(List<QueryGoodsListResponse> queryGoodsList,List goodsIdList) {
        if (org.apache.commons.collections.CollectionUtils.isEmpty(goodsIdList)) {
            return queryGoodsList;
        }
        if (org.apache.commons.collections.CollectionUtils.isEmpty(queryGoodsList)) {
            return queryGoodsList;
        }
        Set<String> goodsIdSet = new HashSet();
        for (Object goodsId : goodsIdList) {
            goodsIdSet.add(goodsId.toString());
        }
        List list = new ArrayList();
        for (String goodsId : goodsIdSet) {
            boolean flg = false;
            for (QueryGoodsListResponse queryGoodsListResponse : queryGoodsList) {
                flg = false;
                if (org.apache.commons.collections.CollectionUtils.isNotEmpty(queryGoodsListResponse.getGoodsList())) {
                    for (Object goodsObj : queryGoodsListResponse.getGoodsList()) {
                        JSONObject goodsJson = (JSONObject) JSONObject.toJSON(goodsObj);
                        if (goodsId.equals(goodsJson.getString("id"))) {
                            list.add(goodsObj);
                            flg = true;
                            break;
                        }
                    }
                }
                if (flg) break;
            }
        }
        if (CollectionUtils.isEmpty(list)) {
            return queryGoodsList;
        }
        QueryGoodsListResponse queryGoodsListResponse = new QueryGoodsListResponse();
        //端上构造的虚假常用货品类目,库中无该类目
        queryGoodsListResponse.setLabel("常用货品");
        queryGoodsListResponse.setGoodsList(list);

        List<QueryGoodsListResponse> queryGoodsListResponseList = new ArrayList<>();
        queryGoodsListResponseList.add(queryGoodsListResponse);
        queryGoodsListResponseList.addAll(queryGoodsList);

        return queryGoodsListResponseList;
    }

    private static Date getTodayAt10AM() {
        // 获取当前日期的Calendar对象
        Calendar calendar = Calendar.getInstance();

        // 设置时间为10:00
        calendar.set(Calendar.HOUR_OF_DAY, 10);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);

        // 将Calendar对象转换为Date对象
        Date todayAt10AM = calendar.getTime();

        return todayAt10AM;
    }


}
